package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<AddressBook> addressBooks = addressBookMapper.list(addressBook);
        return addressBooks;
    }

    @Override
    public AddressBook getDefaultAddress() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(StatusConstant.ENABLE)
                .build();
        //查询是否有默认地址
        AddressBook defaultAddress = addressBookMapper.list(addressBook).get(0);
        return defaultAddress;
    }

    @Transactional
    @Override
    public void setDeafultAddress(AddressBook addressBook) {
        Long id=addressBook.getId();
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBook.setUserId(BaseContext.getCurrentId());
        //查询是否有默认地址
        List<AddressBook> list = addressBookMapper.list(addressBook);
        //存在默认地址，进行修改
        if(list!=null&&list.size()>0){
            addressBook.setId(list.get(0).getId());
            addressBook.setIsDefault(StatusConstant.DISABLE);
            addressBookMapper.update(addressBook);
        }
        addressBook.setId(id);
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.update(addressBook);

    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.deleteById(id);
    }
}
